package com.chukun.multi.serialthreadconfinement.reusable;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author chukun
 *  串行线程封闭示例代码
 */
public class ReusableCodeExample {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        SomeService ss = new SomeService();
        ss.init();
        Future<String> future = ss.doSomething("serial thread confinement....", 1);

        TimeUnit.MILLISECONDS.sleep(50);

        System.out.println(future.get());

        ss.shutdown();
    }

    private static class Task{
        public final String message;
        public final int id;

        public  Task(String message,int id) {
            this.message = message;
            this.id = id;
        }
    }

    private static class SomeService extends AbstractSerializer<Task,String> {

        public SomeService(){
            super(new ArrayBlockingQueue<>(100),
                    new TaskProcessor<Task, String>() {
                        @Override
                        public String doProcess(Task task) throws Exception {
                            System.out.println("["+task.id+"]:"+task.message);
                            return task.message+" accepted....";
                        }
                    });
        }

        @Override
        protected Task makeTask(Object... params) {
            String message = (String) params[0];
            int id = (Integer) params[1];
            return new Task(message,id);
        }

        public Future<String> doSomething(Object...params) throws InterruptedException {
            Future<String> future = null;
            future = service(params);
            return future;
        }

    }
}
